package controllers

import (
	"crypto/md5"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"time"

	"github.com/beego/beego/v2/server/web"
)

type LoginController struct {
	BaseController
}

func (c *LoginController) Prepare() {
	c.BaseController.Prepare()
	c.EnableXSRF = false
}

func generateToken(username string, isSecondPassword bool) string {
	// 简单的token生成方式：md5(username + timestamp + secret)
	timestamp := time.Now().Unix()
	secret := "your-secret-key" // 建议从配置文件读取
	str := fmt.Sprintf("%s%d%s%v", username, timestamp, secret, isSecondPassword)
	hash := md5.Sum([]byte(str))
	return fmt.Sprintf("%x", hash)
}

func (c *LoginController) Login() {
	body, err := ioutil.ReadAll(c.Ctx.Request.Body)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "读取请求数据失败",
		}
		c.ServeJSON()
		return
	}

	var loginData struct {
		Username string `json:"username"`
		Password string `json:"password"`
	}

	if err := json.Unmarshal(body, &loginData); err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的请求数据: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	configUsername, _ := web.AppConfig.String("admin_username")
	configPassword, _ := web.AppConfig.String("admin_password")
	secondPassword, _ := web.AppConfig.String("second_password")

	if loginData.Username == configUsername {
		if loginData.Password == configPassword {
			// 生成token
			token := generateToken(loginData.Username, false)
			c.Data["json"] = map[string]interface{}{
				"success":          true,
				"isSecondPassword": false,
				"token":            token,
			}
		} else if loginData.Password == secondPassword {
			// 生成第二密码的token
			token := generateToken(loginData.Username, true)
			c.Data["json"] = map[string]interface{}{
				"success":          true,
				"isSecondPassword": true,
				"token":            token,
			}
		} else {
			c.Data["json"] = map[string]interface{}{
				"success": false,
				"message": "密码错误",
			}
		}
	} else {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "用户名错误",
		}
	}
	c.ServeJSON()
}
